﻿using PEProtocol;

/**
 * 强化升级系统
 */
public class StrongSys{
    private static StrongSys instance = null;

    public static StrongSys Instance{
        get{
            if (instance == null){
                instance = new StrongSys();
            }

            return instance;
        }
    }

    private CacheSvc cacheSvc;

    public void Init(){
        cacheSvc = CacheSvc.Instance;
        PECommon.Log("StrongSys Init Done");
    }

    public void ReqStrong(MsgPack pkt){
        ReqStrong data = pkt.msg.reqStrong;
        GameMsg msg = new GameMsg{
            cmd = (int)CMD.ResStrong
        };

        PlayerData pd = cacheSvc.GetPlayerDataBySession(pkt.session);
        int curStarLv = pd.strongArr[data.pos];
        StrongCfg nextSc = CfgSvc.Instance.GetStronCfg(data.pos, curStarLv + 1);
        //条件判断
        if (pd.level < nextSc.minlv){
            msg.err = (int) ErrorCode.LackLevel;
        }
        else if (pd.coin < nextSc.coin){
            msg.err = (int) ErrorCode.LackCoin;
        }
        else if (pd.crystal < nextSc.crystal){
            msg.err = (int) ErrorCode.LackCrystal;
        }
        else{
            //任务进度数据更新
            TaskSys.Instance.CalcTaskPrgs(pd, 3);
            
            //资源扣除
            pd.coin -= nextSc.coin;
            pd.crystal -= nextSc.crystal;
            pd.strongArr[data.pos] += 1;
            
            //增加属性
            pd.hp += nextSc.addhp;
            pd.ad += nextSc.addhurt;
            pd.ap += nextSc.addhurt;
            pd.addef += nextSc.adddef;
            pd.apdef += nextSc.adddef;
        }

        //更新数据库
        if (!cacheSvc.UpdatePlayerData(pd.id, pd)){
            msg.err = (int) ErrorCode.UpdateDBError;
        }
        else{
            msg.resStrong = new ResStrong{
                coin = pd.coin,
                crystal = pd.crystal,
                hp = pd.hp,
                ad = pd.ad,
                ap = pd.ap,
                addef = pd.addef,
                apdef = pd.apdef,
                strongArr = pd.strongArr
            };
        }
        
        pkt.session.SendMsg(msg);
    }
}